'use client';

import {useEffect, useState} from 'react';
import Link from 'next/link';
import {getObj, postObj} from "@/services/api_service";
import styles from './AdminDashboardPage.module.css';
import Button from "@/components/ui/Button/Button";
import clsx from "clsx";

type Route = {
    id: number;
    departure_port: {
        name: string;
    };
    arrival_port: {
        name: string;
    };
};

type Port = {
    id: number;
    name: string;
    location: string;
};

type TypeFerry = {
    id: number;
    name: string;
    ferry_type: string;
    is_available: boolean;
    passenger_capacity: number;
    vehicle_capacity: number;
    passenger_filled: number;
    vehicle_filled: number;
};

type Voyage = {
    id: number;
    ferry: TypeFerry;
    route: Route;
    departure_time: string;
    arrival_time: string;
    status: string;
};

export default function AdminDashboardPage() {
    const [currentRoutes, setCurrentRoutes] = useState<Route[]>([]);
    const [currentFerries, setCurrentFerries] = useState<TypeFerry[]>([]);
    const [ports, setPorts] = useState<Port[]>([]);
    const [newPort, setNewPort] = useState({name: '', location: ''});
    const [newRoute, setNewRoute] = useState({departure_port: '', arrival_port: ''});
    const [voyages, setVoyages] = useState<Voyage[]>([]);

    useEffect(() => {
        async function fetchData() {
            try {
                const [routes, ferries, ports, voyages] = await Promise.all([
                    getObj('/api/planning/routes/'),
                    getObj('/api/ships/ferries/details'),
                    getObj('/api/planning/ports/'),
                    getObj('/api/ships/voyages/started/'),
                ]);
                setCurrentRoutes(routes);
                setCurrentFerries(ferries.results);
                setPorts(ports);
                setVoyages(voyages);
                console.log(ferries)
            } catch (err) {
                console.error('Ошибка загрузки данных:', err);
            }
        }

        fetchData();
    }, []);

    const handleAddPort = async () => {
        try {
            await postObj('/api/planning/ports/', newPort);
            setNewPort({name: '', location: ''});
            const updatedPorts = await getObj('/api/planning/ports/');
            setPorts(updatedPorts);
        } catch (err) {
            console.error('Ошибка добавления порта:', err);
        }
    };

    const handleAddRoute = async () => {
        try {
            const departure_port_id = parseInt(newRoute.departure_port);
            const arrival_port_id = parseInt(newRoute.arrival_port);
            await postObj('/api/planning/routes/', {
                departure_port_id: departure_port_id,
                arrival_port_id: arrival_port_id
            });
            setNewRoute({departure_port: '', arrival_port: ''});
            const updatedRoutes = await getObj('/api/planning/routes/');
            setCurrentRoutes(updatedRoutes);
        } catch (err) {
            console.error('Ошибка добавления маршрута:', err);
        }
    };

    return (
        <div className={styles.adminDashboard}>
            <header className={styles.header}>
                <h1>Панель администратора</h1>
                <Link href="/api/sec/admin/" className={styles.adminPanelButton}>
                    Перейти в главную панель
                </Link>
            </header>
            <div className={styles.infoBlocks}>
                <section className={styles.infoBlock}>
                    <h2>Рейсы переправы</h2>
                    <ul className={styles.list}>
                        {currentRoutes.map(route => (
                            <li key={route.id} className={styles.listItem}>
                                {route.departure_port.name} - {route.arrival_port.name}
                            </li>
                        ))}
                    </ul>
                </section>
                <section className={styles.infoBlock}>
                    <h2>Состояние паромов</h2>
                    <ul className={styles.list}>
                        {currentFerries.map(ferry => (
                            <li key={ferry.id} className={styles.listItem}>
                                <strong>{ferry.name}:</strong> <span className={clsx(
                                {
                                    [styles.textAvailable]: ferry.is_available,
                                    [styles.textNotAvailable]: !ferry.is_available,
                                }
                            )}>{ferry.is_available ? 'Свободен' : 'Занят'}</span>
                                <div>Пассажиры: {ferry.passenger_filled}/{ferry.passenger_capacity}</div>
                                <div>Транспортные средства: {ferry.vehicle_filled}/{ferry.vehicle_capacity}</div>
                            </li>
                        ))}
                    </ul>
                </section>
                <section className={styles.infoBlock}>
                    <h2>Отправленные рейсы</h2>
                    <ul className={styles.list}>
                        {voyages?.map(voyage => (
                            <li key={voyage.id} className={styles.listItem}>
                                {voyage.route.departure_port.name} - {voyage.route.arrival_port.name} (Паром: {voyage.ferry.name})
                                <p>Статус: {voyage.status}</p>
                            </li>
                        ))}
                    </ul>
                </section>
                <section className={styles.addBlock}>
                    <section className={styles.infoBlock}>
                        <h2>Добавить новый порт</h2>
                        <input
                            type="text"
                            placeholder="Название порта"
                            value={newPort.name}
                            onChange={e => setNewPort({...newPort, name: e.target.value})}
                            className={styles.input}
                        />
                        <input
                            type="text"
                            placeholder="Местоположение порта"
                            value={newPort.location}
                            onChange={e => setNewPort({...newPort, location: e.target.value})}
                            className={styles.input}
                        />
                        <Button type="button" kind="submit" onClick={handleAddPort} content="Добавить порт"/>
                    </section>
                    <section className={styles.infoBlock}>
                        <h2>Добавить новый маршрут</h2>
                        <select
                            value={newRoute.departure_port}
                            onChange={e => setNewRoute({...newRoute, departure_port: e.target.value})}
                            className={styles.select}
                        >
                            <option value="">Выберите порт отправления</option>
                            {ports.map(port => (
                                <option key={port.id} value={port.id}>
                                    {port.name}
                                </option>
                            ))}
                        </select>
                        <select
                            value={newRoute.arrival_port}
                            onChange={e => setNewRoute({...newRoute, arrival_port: e.target.value})}
                            className={styles.select}
                        >
                            <option value="">Выберите порт прибытия</option>
                            {ports.map(port => (
                                <option key={port.id} value={port.id}>
                                    {port.name}
                                </option>
                            ))}
                        </select>
                        <Button type="button" kind="submit" onClick={handleAddRoute} content="Добавить маршрут"/>
                    </section>
                </section>
            </div>
        </div>
    );
}
